define(["jquery", "easy-admin", "treetable", "iconPickerFa", "autocomplete"], function ($, ea) {

    var table = layui.table,
        treetable = layui.treetable,
        iconPickerFa = layui.iconPickerFa,
        colorpicker = layui.colorpicker,
        laydate = layui.laydate,
        autocomplete = layui.autocomplete;

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'ces.ces/index'+parameter,
        add_url: 'ces.ces/add'+parameter,
        delete_url: 'ces.ces/delete',
        edit_url: 'ces.ces/edit',
        modify_url: 'ces.ces/modify',
        export_url: 'ces.ces/export',
    };
    var Controller = {
        index: function () {
            var init = {
                table_elem: '#currentTable',
                table_render_id: 'currentTableRenderId',
                index_url: (shuju.url.index_url?shuju.url.index_url:shuju.action)+parameter,
                add_url: shuju.url.add_url+parameter,
                delete_url: shuju.url.delete_url,
                edit_url: shuju.url.edit_url,
                modify_url: shuju.url.modify_url,
                export_url: shuju.url.export_url,
            };
            // shuju.limits = JSON.parse(shuju.limits);
            var toolbar = shuju.defaultToolbar;
            var operat = shuju.defaultOperat;
            if(shuju.toolbar){
                var jiaint = toolbar.length;
                toolbar[jiaint] = [];
                // console.log(toolbar);
                $.each(shuju.toolbar,function (i,v){
                    var newobj = {};
                    $.each(v,function (is,vs){
                        newobj[is] = vs;
                    })
                    toolbar[jiaint].push(newobj);
                })
                console.log(toolbar)
            }
            if(shuju.operat.button){
                var jiaints = operat.length;
                operat[jiaints] = [];
                $.each(shuju.operat.button,function (i,v){
                    var newobj = {};
                    $.each(v,function (is,vs){
                        newobj[is] = vs;
                    })
                    operat[jiaint].push(newobj);
                })
            }
            var rows = [];
            rows.push({type: "checkbox"});
            rows.push({field: 'id',  title: 'ID',search:false,totalRowText: '合计',width:80});
            $.each(shuju.row,function (ib,vb){
                if(vb.templet){
                    vb.templet = eval(vb.templet);
                }
                rows.push(vb);
            })
            rows.push({
                width: shuju.operat.width,
                title: shuju.operat.text,
                templet: ea.table.tool,
                operat:operat,
            })
            console.log(rows)
            // return
            ea.table.render({
                init: init,
                cellMinWidth:100,
                page:shuju.ispage,
                limits:shuju.limits,

                toolbar:toolbar,
                // cols: [[
                //     {type: "checkbox"},
                //     {field: 'id',  title: 'ID',search:false,totalRowText: '合计',width:80},
                //     {field: 'name', title: '名称',search:false},
                //     {field: 'kaiguan', title: '状态',  search: false, selectList:{0:"失败",1:'成功'}, templet: ea.table.list,width:200},
                //
                //     {
                //         width: 200,
                //         title: '操作',
                //         templet: ea.table.tool,
                //         operat:operat,
                //     }
                // ]],
                cols:[
                    rows
                ]
            });

            // renderTable();

            $('body').on('click', '[data-treetable-refresh]', function () {
                renderTable();
            });

            $('body').on('click', '[data-treetable-delete]', function () {
                var tableId = $(this).attr('data-treetable-delete'),
                    url = $(this).attr('data-url');
                tableId = tableId || init.table_render_id;
                url = url != undefined ? ea.url(url) : window.location.href;
                var checkStatus = table.checkStatus(tableId),
                    data = checkStatus.data;
                if (data.length <= 0) {
                    ea.msg.error('请勾选需要删除的数据');
                    return false;
                }
                var ids = [];
                $.each(data, function (i, v) {
                    ids.push(v.id);
                });
                ea.msg.confirm('确定删除？', function () {
                    ea.request.post({
                        url: url,
                        data: {
                            id: ids
                        },
                    }, function (res) {
                        ea.msg.success(res.msg, function () {
                            renderTable();
                        });
                    });
                });
                return false;
            });
            ea.table.listenSwitch({filter: 'status', url: init.modify_url});

            ea.table.listenEdit(init, 'currentTable', init.table_render_id, true);

            ea.listen();
        },
        add: function () {
            var tree = layui.tree;
            $(".demo-tree-more").each(function (i,v){
                console.log($(v))
                var url = $(v)[0].dataset.url;
                var show_id = $(v)[0].dataset.contentid;
                var name = $(v)[0].dataset.name
                var table = $(v)[0].dataset.table
                var relationship = $(v)[0].dataset.relationship
                function each(data){
                    $.each(data,function (i,v){
                        if(!v.title){
                            v.title = v.name;
                        }
                        if(v.children){
                            v.children = each(v.children);
                        }
                        data[i] = v;
                    })
                    return data;
                }
                $.post(url,{table:table,name:name,relationship_primary_key:relationship,formtype:'treecheckbox'},function (res){
                    var datas = res.data || [];
                    datas = each(datas);
                    console.log(datas)
                    tree.render({
                        elem: '#'+show_id,
                        data: datas,
                        showCheckbox: true,
                        id: show_id+"ids",
                    });
                    ea.listen(function (data){
                        var checkedData = tree.getChecked(show_id+"ids");
                        var ids = [];
                        $.each(checkedData, function (i, v) {
                            ids.push(v.id);
                            if (v.children !== undefined && v.children.length > 0) {
                                $.each(v.children, function (ii, vv) {
                                    ids.push(vv.id);
                                });
                            }
                        });
                        data[show_id] = JSON.stringify(ids);
                        return data;
                    })
                })
            })
            var time = 0;
            $(document).on('click','[data-type=tianjia]',function (e){
                var field = e.target.dataset.value;
                console.log(field);
                var html = "<div class=\"layui-row\">\n" +
                    "                        <div class=\"layui-form-mid\">键：</div><input class=\"layui-input layui-input-inline\" style=\"width: 100px\" name=\""+field+"[key][]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\">值：</div><input class=\"layui-input layui-input-inline\" style=\"width: 150px\" name=\""+field+"[value][]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\"><input type=\"button\" data-type=\"jian\" class=\"layui-btn layui-btn-sm layui-btn-primary layui-border-red\" value=\"-\"></div>\n" +
                    "                    </div>"
                $(this).parent().parent().append(html)
            })
            $(document).on('click','[data-type=jian]',function (e){
                // console.log(e);
                $(this).parent().parent().remove();
            })
            $(".aselect").bind('input propertychange',function (data){
                var value = $(this).val();
                var url = data.target.dataset.url;
                var show_id = data.target.dataset.contentid;
                var name = data.target.dataset.name
                var table = data.target.dataset.table
                var relationship = data.target.dataset.relationship
                // console.log(data)
                // console.log(show_id)
                // console.log(name)
                // console.log(table)
                // console.log(relationship)
                // console.log(url)
                // return
                time = new Date().getTime();
                setTimeout(function (){
                    var newtime = new Date().getTime();
                    if(newtime>=time+499){
                        $.post(url,{table:table,value:value,name:name,relationship_primary_key:relationship,field:show_id},function (res){
                            // console.log(res);
                            var select_show = $("#"+show_id);
                            select_show.empty();
                            if(res.data.length>0){
                                var str = '<dd class="xuanzes" data-value="" class="">请选择</dd>';
                                $.each(res.data,function (i,v){
                                    str +='<dd class="xuanzes" data-value="' + v[relationship] + '" class="">' + v[name] + '</dd>';
                                })
                                select_show.append(str)
                                select_show.show();
                            }else{
                                select_show.hide();
                            }
                        })
                        $('body').on('click','dd',function (data){
                            console.log(data);
                            var value = data.target.dataset.value;
                            var text = data.target.innerText;
                            // $(this).parent().prev().children('input')
                            // console.log($(this).parent().prev().children('input'))
                            $.each($(this).parent().prev().children('input'),function (i,v){
                                if(i==1){
                                    $(v).val(value);
                                }else if(i==0){
                                    $(v).val(text);
                                }
                            })
                            $(this).parent().hide();
                        })
                    }else{
                        console.log('时间没到');
                    }
                },500);
            })
            $(".icon").each(function (i,v) {
                var ids = $(v).attr('id');
                var myiconPickerFa = iconPickerFa.render({
                    elem:"#"+ids,
                    url: PATH_CONFIG.iconLess,
                    limit: 12,
                    click: function (data) {
                        $('#'+ids).val('fa ' + data.icon);
                    },
                    success: function (d) {
                        console.log(d);
                    }
                })
            })
            $(".color").each(function (i,v) {
                var ids = $(v).attr('id');
                var coles = $('[name='+ids+']').val();
                //初始色值
                var mycolorpicker = colorpicker.render({
                    elem: '#'+ids
                    ,color: coles //设置默认色
                    ,change:function (color) {
                        $('[name='+ids+']').val(color);
                    }
                });
            })
            $(".datetime").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'datetime'
                });
            })
            ea.listen(function (data) {
                console.log(data)
                return data;
            }, function (res) {
                console.log(res);
                ea.msg.success(res.msg, function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.$('[data-treetable-refresh]').trigger("click");
                });
            });
        },
        edit: function () {
            var tree = layui.tree;
            $(".demo-tree-more").each(function (i,v){
                console.log($(v))
                var url = $(v)[0].dataset.url;
                var show_id = $(v)[0].dataset.showid;
                var id = $(v).attr('id');
                var showname = $(v)[0].dataset.showname
                var value = $(v)[0].dataset.value;
                console.log(url);
                console.log(show_id);
                console.log(showname);
                console.log(value);
                console.log(id);
                // return
                if(value){
                    value = JSON.parse(value)
                    // console.log(value)
                }
                function eachs(data){
                    $.each(data,function (i,v){
                        if(!v.title){
                            v.title = v.name;
                            console.log(v.name)
                        }
                        if($.inArray(v[show_id],value)==-1){
                            v.checked = false;
                        }else{
                            v.checked = true;
                        }
                        // v.checked = false;
                        // console.log(v.checked);
                        if(v.children){
                            v.checked = false;
                            v.children = eachs(v.children);
                        }
                        data[i] = v;
                    })
                    return data;
                }
                $.post(url,{name:name,value:value,formtype:'treecheckbox'},function (res){
                    var datas = res.data || [];
                    datas = eachs(datas);
                    // console.log('haha')
                    console.log(datas)
                    // return
                    tree.render({
                        elem: '#'+id,
                        data: datas,
                        showCheckbox: true,
                        id: id+"ids",
                    });
                    ea.listen(function (data){
                        var checkedData = tree.getChecked(id+"ids");
                        var ids = [];
                        $.each(checkedData, function (i, v) {
                            ids.push(v[show_id]);
                            if (v.children !== undefined && v.children.length > 0) {
                                $.each(v.children, function (ii, vv) {
                                    ids.push(vv[show_id]);
                                });
                            }
                        });
                        data[id] = JSON.stringify(ids);
                        // console.log(data);
                        return data;
                    })
                })
            })
            var time = 0;
            $(document).on('click','[data-type=tianjia]',function (e){
                console.log(e.target.dataset.value);
                var field = e.target.dataset.value;
                var index = parseInt(e.target.dataset.index);
                console.log(index);
                index++
                $(this).attr('data-index',index);
                // return
                var html = "<div class=\"layui-row\">\n" +
                    "                        <div class=\"layui-form-mid\">键：</div><input class=\"layui-input layui-input-inline\" style=\"width: 100px\" name=\""+field+"[key]["+index+"]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\">值：</div><input class=\"layui-input layui-input-inline\" style=\"width: 150px\" name=\""+field+"[value]["+index+"]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\"><input type=\"button\" data-type=\"jian\" class=\"layui-btn layui-btn-sm layui-btn-primary layui-border-red\" value=\"-\"></div>\n" +
                    "                    </div>"
                $(this).parent().parent().parent().append(html)
            })
            $(document).on('click','[data-type=jian]',function (e){
                console.log(e);
                $(this).parent().parent().remove();
            })
            $(".aselect").bind('input propertychange',function (data){
                var value = $(this).val();
                var url = data.target.dataset.url;
                var show_id = data.target.dataset.contentid;
                var name = data.target.dataset.name
                var table = data.target.dataset.table
                var relationship = data.target.dataset.relationship
                // console.log(data)
                // console.log(show_id)
                // console.log(name)
                // console.log(table)
                // console.log(relationship)
                // console.log(url)
                // return
                time = new Date().getTime();
                setTimeout(function (){
                    var newtime = new Date().getTime();
                    if(newtime>=time+499){
                        $.post(url,{table:table,value:value,name:name,relationship_primary_key:relationship,field:show_id},function (res){
                            // console.log(res);
                            var select_show = $("#"+show_id);
                            select_show.empty();
                            if(res.data.length>0){
                                var str = '<dd class="xuanzes" data-value="" class="">请选择</dd>';
                                $.each(res.data,function (i,v){
                                    str +='<dd class="xuanzes" data-value="' + v[relationship] + '" class="">' + v[name] + '</dd>';
                                })
                                select_show.append(str)
                                select_show.show();
                            }else{
                                select_show.hide();
                            }
                        })
                        $('body').on('click','dd',function (data){
                            console.log(data);
                            var value = data.target.dataset.value;
                            var text = data.target.innerText;
                            // $(this).parent().prev().children('input')
                            // console.log($(this).parent().prev().children('input'))
                            $.each($(this).parent().prev().children('input'),function (i,v){
                                if(i==1){
                                    $(v).val(value);
                                }else if(i==0){
                                    $(v).val(text);
                                }
                            })
                            $(this).parent().hide();
                        })
                    }else{
                        console.log('时间没到');
                    }
                },500);
            })
            $(".icon").each(function (i,v) {
                var ids = $(v).attr('id');
                var myiconPickerFa = iconPickerFa.render({
                    elem:"#"+ids,
                    url: PATH_CONFIG.iconLess,
                    limit: 12,
                    click: function (data) {
                        $('#'+ids).val('fa ' + data.icon);
                    },
                    success: function (d) {
                        console.log(d);
                    }
                })
            })
            $(".color").each(function (i,v) {
                var ids = $(v).attr('id');
                var coles = $('[name='+ids+']').val();
                //初始色值
                var mycolorpicker = colorpicker.render({
                    elem: '#'+ids
                    ,color: coles //设置默认色
                    ,change:function (color) {
                        $('[name='+ids+']').val(color);
                    }
                });
            })
            $(".datetime").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'datetime'
                });
            })
            $(".date").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'date'
                });
            })
            $(".time").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'time'
                });
            })
            ea.listen(function (data) {
                console.log(data)
                return data;
            }, function (res) {
                console.log(res);
                ea.msg.success(res.msg, function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.$('[data-treetable-refresh]').trigger("click");
                });
            });
        },
        details:function(){
            var tree = layui.tree;
            $(".demo-tree-more").each(function (i,v){
                console.log($(v))
                var url = $(v)[0].dataset.url;
                var show_id = $(v)[0].dataset.contentid;
                var name = $(v)[0].dataset.name
                var table = $(v)[0].dataset.table
                var relationship = $(v)[0].dataset.relationship
                var value = $(v)[0].dataset.value;
                // console.log('haha')
                // console.log(value)
                if(value){
                    value = JSON.parse(value)
                    // console.log(value)
                }
                function each(data){
                    $.each(data,function (i,v){
                        if(!v.title){
                            v.title = v.name;
                        }
                        if($.inArray(v[relationship],value)==-1){
                            v.checked = false;
                        }else{
                            v.checked = true;
                        }
                        // v.checked = false;
                        // console.log(v.checked);
                        if(v.children){
                            v.checked = false;
                            v.children = each(v.children);
                        }
                        data[i] = v;
                    })
                    return data;
                }
                $.post(url,{table:table,name:name,relationship_primary_key:relationship,formtype:'treecheckbox'},function (res){
                    var datas = res.data || [];
                    datas = each(datas);
                    console.log('haha')
                    console.log(datas)
                    tree.render({
                        elem: '#'+show_id,
                        data: datas,
                        showCheckbox: true,
                        id: show_id+"ids",
                    });
                    ea.listen(function (data){
                        var checkedData = tree.getChecked(show_id+"ids");
                        var ids = [];
                        $.each(checkedData, function (i, v) {
                            ids.push(v.id);
                            if (v.children !== undefined && v.children.length > 0) {
                                $.each(v.children, function (ii, vv) {
                                    ids.push(vv.id);
                                });
                            }
                        });
                        data[show_id] = JSON.stringify(ids);
                        // console.log(data);
                        return data;
                    })
                })
            })
            var time = 0;
            $(document).on('click','[data-type=tianjia]',function (e){
                var html = "<div class=\"layui-row\">\n" +
                    "                        <div class=\"layui-form-mid\">键：</div><input class=\"layui-input layui-input-inline\" style=\"width: 100px\" name=\""+field+"[key][]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\">值：</div><input class=\"layui-input layui-input-inline\" style=\"width: 150px\" name=\""+field+"[value][]\" value=\"\">\n" +
                    "                        <div class=\"layui-form-mid\"><input type=\"button\" data-type=\"jian\" class=\"layui-btn layui-btn-sm layui-btn-primary layui-border-red\" value=\"-\"></div>\n" +
                    "                    </div>"
                $(this).parent().parent().append(html)
            })
            $(document).on('click','[data-type=jian]',function (e){
                console.log(e);
                $(this).parent().parent().remove();
            })
            $(".aselect").bind('input propertychange',function (data){
                var value = $(this).val();
                var url = data.target.dataset.url;
                var show_id = data.target.dataset.contentid;
                var name = data.target.dataset.name
                var table = data.target.dataset.table
                var relationship = data.target.dataset.relationship
                // console.log(data)
                // console.log(show_id)
                // console.log(name)
                // console.log(table)
                // console.log(relationship)
                // console.log(url)
                // return
                time = new Date().getTime();
                setTimeout(function (){
                    var newtime = new Date().getTime();
                    if(newtime>=time+499){
                        $.post(url,{table:table,value:value,name:name,relationship_primary_key:relationship,field:show_id},function (res){
                            // console.log(res);
                            var select_show = $("#"+show_id);
                            select_show.empty();
                            if(res.data.length>0){
                                var str = '<dd class="xuanzes" data-value="" class="">请选择</dd>';
                                $.each(res.data,function (i,v){
                                    str +='<dd class="xuanzes" data-value="' + v[relationship] + '" class="">' + v[name] + '</dd>';
                                })
                                select_show.append(str)
                                select_show.show();
                            }else{
                                select_show.hide();
                            }
                        })
                        $('body').on('click','dd',function (data){
                            console.log(data);
                            var value = data.target.dataset.value;
                            var text = data.target.innerText;
                            // $(this).parent().prev().children('input')
                            // console.log($(this).parent().prev().children('input'))
                            $.each($(this).parent().prev().children('input'),function (i,v){
                                if(i==1){
                                    $(v).val(value);
                                }else if(i==0){
                                    $(v).val(text);
                                }
                            })
                            $(this).parent().hide();
                        })
                    }else{
                        console.log('时间没到');
                    }
                },500);
            })
            $(".icon").each(function (i,v) {
                var ids = $(v).attr('id');
                var myiconPickerFa = iconPickerFa.render({
                    elem:"#"+ids,
                    url: PATH_CONFIG.iconLess,
                    limit: 12,
                    click: function (data) {
                        $('#'+ids).val('fa ' + data.icon);
                    },
                    success: function (d) {
                        console.log(d);
                    }
                })
            })
            $(".color").each(function (i,v) {
                var ids = $(v).attr('id');
                var coles = $('[name='+ids+']').val();
                //初始色值
                var mycolorpicker = colorpicker.render({
                    elem: '#'+ids
                    ,color: coles //设置默认色
                    ,change:function (color) {
                        $('[name='+ids+']').val(color);
                    }
                });
            })
            $(".datetime").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'datetime'
                });
            })
            $(".date").each(function (i,v) {
                var ids = $(v).attr('id');
                laydate.render({
                    elem: '#'+ids
                    ,type: 'date'
                });
            })
            ea.listen(function (data) {
                console.log(data)
                return data;
            }, function (res) {
                console.log(res);
                ea.msg.success(res.msg, function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.$('[data-treetable-refresh]').trigger("click");
                });
            });
        }
    };
    return Controller;
});
